package com.doubao.notepad_blog_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doubao.notepad_blog_backend.common.api.ApiResult;
import com.doubao.notepad_blog_backend.domain.BmsPost;
import com.doubao.notepad_blog_backend.domain.BmsTag;
import com.doubao.notepad_blog_backend.service.BmsTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/tag")
@Api(value = "标签管理",tags = {"标签管理"})
public class BmsTagController  {

    @Resource
    private BmsTagService tagService;

    @ApiOperation( "根据标签名查文章" )
    @GetMapping("/{name}")
    public ApiResult<Map<String, Object>> getPostsByTag(
            @PathVariable("name") String tagName,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size) {

        Map<String, Object> map = new HashMap<>(16);

        LambdaQueryWrapper<BmsTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BmsTag::getName, tagName);
        BmsTag one = tagService.getOne(wrapper);
        Assert.notNull(one, "话题不存在，或已被管理员删除");
        Page<BmsPost> posts = tagService.selectPostsByTagId(new Page<>(page, size), one.getId());
        // 其他热门标签
        Page<BmsTag> hotTags = tagService.page(new Page<>(1, 10),
                new LambdaQueryWrapper<BmsTag>()
                        .notIn(BmsTag::getName, tagName)
                        .orderByDesc(BmsTag::getPostCount));

        map.put("posts", posts);
        map.put("hotTags", hotTags);

        return ApiResult.success(map);
    }

}

